package com.movw.controller;

import com.movw.beans.User;
import com.movw.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@SessionAttributes(value = {"names", "age"})
@Controller
public class hello {
    @Autowired
    private AdminService adminService;
    @RequestMapping("/out")
    public String out(HttpSession session, SessionStatus sessionStatus) {
        session.removeAttribute("names");
        sessionStatus.setComplete();
//        sessionStatus只清除SessionAttributes声明的session
        return "hello";
    }
    /**
     * 用户登录
     *
     * @param httpSession 存放登录的session
     * @param passwd    密码
     * @param username    名字
     * @return
     */
    @RequestMapping(value = "/login_data", method = RequestMethod.POST)
    public ModelAndView login(HttpSession httpSession, String username, String passwd) {
        User user=adminService.findUserByName(username);
        if(user.getUserpwd().equals(passwd)){
            httpSession.setAttribute("username", username);//存放session
            return new ModelAndView("loginSuccess");
        }
        return new ModelAndView("error");
    }

    /**
     * 管理员登录
     *
     * @param httpSession 存放登录的session
     * @param password    密码
     * @param username    名字
     * @return
     */
    @RequestMapping(value = "/Adminlogin_data", method = RequestMethod.POST)
    public ModelAndView adminLogin(HttpSession httpSession, String username, String password) {
        System.out.println(username + password);
        httpSession.setAttribute("username", "admin");//存放session
        return new ModelAndView("loginSuccess");
    }

    /**
     * 登出
     *
     * @param httpSession
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public String logout(HttpSession httpSession) {
        String name1 = (String) httpSession.getAttribute("username");
        System.out.println(name1);
        httpSession.invalidate();//清理session
        try {
            String name = (String) httpSession.getAttribute("username");
            System.out.println(name);
        } catch (Exception e) {
            System.out.println("无");
        }
        return "ok";
    }
}
